<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Cart;
use App\Models\Category;
use App\Models\MallProductStock;
use App\Models\Product;
use App\Models\Tag;
use App\Services\MallOrderService;
use Illuminate\Http\Request;

class ZeroProductController extends BaseController
{
    public $model = Product::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $search = ['title' => '', 'category_id' => 0, 'on_status' => 1];
        $input = $request->input();
        $order_by_key = $request->input('order_by_key', 'id');
        $order_by_value = $request->input('order_by_value', 'desc');
        $field = ['id', 'title','parent_category_id', 'category_id', 'producer_id', 'zero_sale_num', 'amount', 'vip_amount', 'image_url'];
        $fac_title = $input['fac_title'] ?? '';

        $list = Product::apply($search, $input)->select($field)->withCertain('category', ['title'])
            ->where('is_zero', 1)
            ->withCertain('parent_category', ['title'])
            ->withCertain('producer', ['fac_title'])
            ->when($fac_title, function ($q)  use($fac_title){
                $q->whereHas('producer', function ($qt) use($fac_title){
                    $qt->where('fac_title', 'like', '%' . $fac_title . '%');
                });
            })
            ->orderBy($order_by_key, $order_by_value)
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $product = Product::find($id);
            if ($product->on_status != 1)
                continue;
            $product->is_zero = 1;
            $product->save();
        }
        return $this->success([]);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
           $model = Product::find($id);
           if (!$model)
               continue;
           $model->is_zero = 0;
           $model->save();
        }
        return $this->success([]);
    }



}

